<template>
  <div
    v-loading="loading"
    v-empty="nopermission"
    class="rc-cont"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.components.b846178db978b99aa42775829715576d')">
    <div v-if="!isSeas" class="rc-head">
      <wk-toggle-button v-if="crmType=='customer'" v-model="showType">
        <wk-toggle-item
          v-for="item in [{name:$t('crm.components.a570dc555704e83b83c7d6cdcf8a752e'), value: 'table', icon: 'wk wk-icon-three-line'}, {name:$t('crm.components.a860480b82c1da3d2194577f63c50b38'), value: 'tree', icon: 'wk wk-icon-org-solid'}]"
          :key="item.value"
          :label="item.name"
          :value="item.value">
          {{ item.name }}
          <i :class="item.icon" />
        </wk-toggle-item>
      </wk-toggle-button>

      <div class="handle">
        <el-button v-if="contactsSave" icon="el-icon-plus" @click="createClick">
          {{ $t('crm.components.070aceb0b9a51cc7cd8bb3273cfc837d') }}
        </el-button>
        <el-button
          v-if="crmType === 'business'"
          @click="showRelativeView = true">
          {{ $t('crm.components.b93c662d1c4d9a26860c4d9358d66b3d') }}
        </el-button>
        <el-button
          v-if="canRelation"
          type="danger"
          @click.native="unRelevanceHandleClick">
          {{ $t('crm.components.672d12b464c1e6fc8b7f7e353eb77673') }}
        </el-button>
        <crm-relative
          v-if="showRelativeView"
          ref="crmrelative"
          :visible.sync="showRelativeView"
          :radio="false"
          :props="{
            params: {
              searchList: [
                { formType:'text',name:'customer_id',type:1,values:[customerId] }
              ]
            }
          }"
          :selected-data="{ 'contacts': list }"
          data-type="contacts"
          @close="showRelativeView = false"
          @changeCheckout="checkRelativeInfos" />
      </div>
    </div>
    <el-table
      v-if="fieldList.length > 0 && showType == 'table'"
      :data="list"
      :height="tableHeight"
      :cell-class-name="cellClassName"
      stripe
      @row-click="handleRowClick"
      @selection-change="selectionList = $event">
      <el-table-column
        v-if="canRelation"
        show-overflow-tooltip
        type="selection"
        align="center"
        width="55" />
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        show-overflow-tooltip />
      <el-table-column
        :label="$t('crm.components.044b2b3769103f96dc18126e35a0eec6')"
        width="120">
        <template slot-scope="scope">
          <flexbox justify="center">
            <span v-if="contactsId == scope.row.contactsId" class="chief">
              <i class="wk wk-success" />
              {{ $t('crm.components.d265a880d83463bd3167708f39e09ade') }}
            </span>
            <el-button
              v-else-if="!isSeas"
              class="set-chief-btn"
              type="primary-text"
              @click.native="setChieflyContacts(scope)">
              {{ $t('crm.components.dc692a18390582df7e4bb1e14fd99d8e') }}
            </el-button>
          </flexbox>
        </template>
      </el-table-column>
    </el-table>

    <div
      v-if="showType == 'tree'"
      :style="{height: `${tableHeight}px`}"
      class="wk-org-tree">
      <vue2-org-tree
        v-for="(item,index) in treeList"
        :key="index"
        :data="item"
        :label-class-name="orgTreeClass"
        :props="{label: 'name', children: 'children', expand: 'expand'}"
        :render-content="renderContent"
        @on-node-click="orgTreeClick"
      />
    </div>
    <c-r-m-full-screen-detail
      :id="detailId"
      :visible.sync="showFullDetail"
      crm-type="contacts"
      @handle="detailHandle" />
    <c-r-m-all-create
      v-if="isCreate"
      :action="createActionInfo"
      crm-type="contacts"
      @save-success="createSaveSuccess"
      @close="isCreate=false" />
  </div>
</template>

<script type="text/javascript">
import CRMAllCreate from './CRMAllCreate'
import {
  crmCustomerSetContactsAPI,
  crmCustomerQueryContactsByIdAPI
} from '@/api/crm/customer'
import {
  crmBusinessQueryContactsAPI,
  crmBusinessRelateContactsAPI,
  crmBusinessUnrelateContactsAPI,
  crmBusinessSetContactsAPI
} from '@/api/crm/business'
import { crmContactsIndexAPI } from '@/api/crm/contacts.js'
import CrmRelative from '@/components/CreateCom/CrmRelative'

import { WkToggleButton, WkToggleItem } from '@/components/NewCom/WkToggleButton/index'

import { getPermissionByKey } from '@/utils'
import crmTypeModel from '@/views/crm/model/crmTypeModel.js'

export default {
  name: 'RelativeContacts', // 相关联系人列表  可能再很多地方展示 放到客户管理目录下
  components: {
    CRMFullScreenDetail: () => import('@/components/CRMFullScreenDetail'),
    CRMAllCreate,
    CrmRelative,
    WkToggleButton,
    WkToggleItem
  },
  mixins: [],
  inject: ['rootTabs'],
  props: {
    // 模块ID
    id: [String, Number],
    // 首要联系人ID
    contactsId: [String, Number],
    // 客户类型
    crmType: {
      type: String,
      default: ''
    },
    // 是公海 默认是客户
    isSeas: {
      type: Boolean,
      default: false
    },
    // 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      nopermission: false,
      showType: 'table', // tree
      list: [],
      fieldList: [],
      treeList: [], // 直属上级架构数据
      tableHeight: '400px',
      showFullDetail: false,
      // 控制新建
      isCreate: false,
      // 查看全屏联系人详情的 ID
      detailId: '',
      // 创建的相关信息
      createActionInfo: { type: 'relative', crmType: this.crmType, data: {}},
      // 关联的逻辑
      showRelativeView: false,
      selectionList: []
    }
  },
  computed: {
    // 联系人下客户id获取关联商机
    customerId() {
      return this.detail.customerId
    },
    // 是否能关联
    canRelation() {
      return this.crmType == 'business'
    },
    contactsSave() {
      return !!getPermissionByKey('crm.contacts.save')
    },
    orgTreeData() {
      if (this.treeList.length > 0) {
        return this.treeList
      }
      return {}
    }
  },
  watch: {
    id(val) {
      this.list = []
      this.getDetail()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeContacts') {
        this.getDetail(false)
      }
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    /**
     * 关联的数据
     */
    checkRelativeInfos(data) {
      if (data.data.length > 0) {
        const params = { businessId: this.id }
        params.contactsIds = data.data
          .map(item => {
            return item.contactsId
          })
        crmBusinessRelateContactsAPI(params)
          .then(res => {
            this.getDetail()
            this.$message.success(this.$t('crm.components.a1dd1289bded86ec414c197f85480f73'))
          })
          .catch(() => {})
      }
    },

    /**
     * 取消关联
     */
    unRelevanceHandleClick() {
      if (this.selectionList.length == 0) {
        this.$message.error(this.$t('crm.components.e8c716f4021ef677085a4f2cec8f6581'))
      } else {
        this.$confirm(
          this.$t('crm.components.ec722e10b2dfeb89b27956b0790e13e5'),
          this.$t('crm.components.2eb918fc021c2a8eee79c1098b1f8988'),
          {
            confirmButtonText: this.$t('crm.components.a5fd57bc180403b8ff50769e1046e665'),
            cancelButtonText: this.$t('crm.components.d76023b882c4d522cbab2c1699749831'),
            type: 'warning'
          }
        )
          .then(() => {
            const params = { businessId: this.id }
            params.contactsIds = this.selectionList
              .map(item => {
                return item.contactsId
              })
            crmBusinessUnrelateContactsAPI(params)
              .then(res => {
                this.getDetail()
                this.$message.success(this.$t('crm.components.4ad19b4ad02350b3bca33d4e81548a03'))
              })
              .catch(() => {})
          })
          .catch(() => {})
      }
    },

    /**
     * 表头数据
     */
    getFieldList() {
      this.fieldList.push({
        prop: 'name',
        width: '200',
        label: this.$t('crm.components.54eb08706e310b07da6ce02622852f1c')
      })
      this.fieldList.push({ prop: 'mobile', width: '200', label: this.$t('crm.components.a3bbee96c721c564787c8700c467ec6c') })
      this.fieldList.push({ prop: 'post', width: '200', label: this.$t('crm.components.99eb90cf108a32a116aa537d06c6c3ea') })
      this.fieldList.push({ prop: 'parentContactsName', width: '200', label: this.$t('crm.components.db87391abbb084b904e310f3b8663b81') })
    },

    /**
     * 获取数据
     */
    getDetail(loading = true) {
      this.loading = loading
      const request = {
        customer: crmContactsIndexAPI,
        business: crmBusinessQueryContactsAPI
      }[this.crmType]
      let params = {
        pageType: 0,
        type: crmTypeModel[this.crmType],
        searchList: [
          {
            'type': 1,
            'values': [
              this.id
            ],
            'formType': 'text',
            'name': `${this.crmType}_id`
          }
        ]
      }
      if (this.crmType == 'business') {
        params = { pageType: 0 }
        params[this.crmType + 'Id'] = this.id
      }
      request(params)
        .then(res => {
          if (this.fieldList.length == 0) {
            this.getFieldList()
          }
          if (this.crmType == 'customer') {
            this.getTreeList()
          }
          this.nopermission = false
          this.loading = false
          this.list = res.data.list
        })
        .catch(data => {
          if (data.code == 102) {
            this.nopermission = true
          }
          this.loading = false
        })
    },
    /**
 * 查询联系人视图结构
 */
    getTreeList() {
      this.loading = true
      crmCustomerQueryContactsByIdAPI({ customerId: this.detail.customerId })
        .then(res => {
          this.treeList = res.data
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
      if (column.property == 'name') {
        this.detailId = row.contactsId
        this.showFullDetail = true
      }
    },
    /**
     * 架构视图点击
     */
    orgTreeClick(e, data) {
      this.detailId = data.contactsId
      this.showFullDetail = true
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'name') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * 新建
     */
    createClick() {
      //  客户 下新建联系人
      if (this.crmType == 'customer') {
        this.createActionInfo.data['customer'] = this.detail
      } else if (this.crmType == 'business') {
        this.createActionInfo.data['customer'] = this.detail
        this.createActionInfo.relativeData = {
          businessId: this.detail.businessId
        }
      }
      this.isCreate = true
    },
    createSaveSuccess() {
      if (this.canRelation) {
        this.$refs.crmrelative && this.$refs.crmrelative.refreshList()
      }

      this.$bus.emit('crm-tab-num-update')
      this.getDetail()
    },

    /**
     * 设置首要联系人
     */
    setChieflyContacts(data) {
      const request = {
        customer: crmCustomerSetContactsAPI,
        business: crmBusinessSetContactsAPI
      }[this.crmType]

      const params = { contactsId: data.row.contactsId }
      params[this.crmType + 'Id'] = this.id
      this.loading = true
      request(params)
        .then(res => {
          this.$message.success(this.$t('crm.components.5e5be57b5a4760aef0ac6fa9f794ef7f'))
          this.$emit('update:contactsId', data.row.contactsId)
          this.loading = false
        })
        .catch(data => {
          this.loading = false
        })
    },

    /**
     * 详情操作
     */
    detailHandle(data) {
      if (data.type === 'delete') {
        this.getDetail()
        this.$nextTick(() => {
          this.$bus.emit('crm-tab-num-update')
        })
      }
    },
    /** ****组织图 */
    renderContent(h, data) {
      return `${data.name}`
    },
    orgTreeClass(data) {
      return 'org-tree-default'
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/relativecrm.scss";

.set-chief-btn {
  padding: 4px 12px;
}

.chief {
  i {
    margin-right: 3px;
    font-size: 14px;
    color: $--color-g300;
  }
}

.rc-head {
  position: relative;
  min-height: 32px;

  .wk-toggle-button {
    position: absolute;
    top: 0;
    left: 0;
  }

  .handle {
    position: absolute;
    top: 0;
    right: 0;
  }
}

.wk-toggle-item {
  display: flex;

  i {
    margin-left: 2px;
  }
}

.wk-org-tree {
  overflow: auto;
}
</style>
